<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { OnActionClickParams, VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDict, queryDictApi } from '#/api';

import { formSchema, useColumns } from './dict.data.ts';
import dictModel from './dictModel.vue';

defineOptions({ name: 'SystemDict' });

interface RowType {
  id: string;
  name: string;
  value: any;
  remark: string;
}

const formOptions: VbenFormProps = {
  schema: formSchema,
  showCollapseButton: false,
  actionButtonsReverse: true,
  // 大屏一行显示4个，中屏一行显示3个，小屏一行显示2个
  wrapperClass: 'grid-cols-2 md:grid-cols-3 lg:grid-cols-4',
};

const gridOptions: VxeGridProps<RowType> = {
  columns: useColumns(onActionClick),
  height: 'auto',
  keepSource: true,
  pagerConfig: { enabled: true, pageSize: 10 },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const params = Object.assign({}, formValues, {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return await getDictTableApi(params);
      },
    },
  },
  stripe: true,
  rowConfig: {
    keyField: 'id',
    isHover: true,
  },
};

/** 查询字典信息 */
async function getDictTableApi(formData) {
  const res = await queryDictApi(formData);
  const { records, total } = res;
  return { items: records, total };
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [Modal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: dictModel,
});

function onActionClick(e: OnActionClickParams) {
  switch (e.code) {
    case 'delete': {
      onDelete(e.row);
      break;
    }
    case 'edit': {
      openModal('edit', e.row);
      break;
    }
  }
}

const onDelete = async (data: any) => {
  const hideLoading = message.loading({
    content: `正在删除${data.name}`,
    duration: 0,
    key: 'action_process_msg',
  });
  deleteDict(data.id)
    .then(() => {
      message.success({
        content: `删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
};
function openModal(type: string, row: object) {
  modalApi.setData({
    type,
    records: row,
  });
  modalApi.setState({ title: type === 'add' ? '字典添加' : '字典编辑' }).open();
}

function onRefresh() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="字典列表">
      <template #toolbar-tools>
        <Button type="primary" @click="openModal('add', {})"> 添加 </Button>
      </template>
    </Grid>
    <!-- 添加编辑弹框 -->
    <Modal @on-success="onRefresh" />
  </Page>
</template>
